package de.blitzcoder.collide.util;

import java.io.OutputStream;
import java.io.PrintStream;
import java.util.LinkedList;
import java.util.ListIterator;


/*
        BlitzMax IDE
 **************************************************
        Copyright (c) 2007-2008 by Johannes Wotzka
        All Rights reserved
        --------------------------------------------------
        File: ide/Log.java
 
        This is a logging-Class used by the whole IDE
 */


/**
 * LOGGING CLASS
 */
public class Log {
    
    // Log Enabled
    static boolean logEnabled = false;

    
    // Add a String
    public static void log(String str) {
        
        if (logEnabled) {
            
            Throwable t = new Throwable();
            StackTraceElement elements[] = t.getStackTrace();
            
            String method = elements[1].getMethodName();
            String clas = elements[1].getClassName();
            int line = elements[1].getLineNumber();
            String fileName = elements[1].getFileName();

            // TODO: Save these infos in a logfile
            String log = "["+fileName+":"+line+"] "+clas.replace("de.blitzcoder.collide.","")+"."+method+" : "+str+'\n';

            System.out.println(str);

            ListIterator<LogListener> it = listenerList.listIterator();
            while (it.hasNext())
                it.next().log(log);
           
        }
        
    }
    
    public static String getStackTrace() {
        Throwable t = new Throwable();
        StackTraceElement e[] = t.getStackTrace();
        String str = "";
        for (int i=0;i<e.length;i++)
            str+=e[i].toString()+"\n";
        return str;
    }
    
    public static void setEnabled(boolean e) {
        logEnabled = e;
    }
    
    /**
     * START LOG
     */
    public static void start() {
        log("********************");
        log("CollIDE Debug Output");
        log("********************");
    }
    
    /**
     * END LOG
     */
    public static void end() {
        log("*********************");
        log("CollIDE Shutting down");
        log("*********************");
    }

    /*
     * Listener
     */
    public static interface LogListener {
        public void log(String txt);
    }
    private static LinkedList<LogListener> listenerList = new LinkedList<Log.LogListener>();
    public static void addListener(LogListener lis) {
        listenerList.addLast(lis);
    }
    
}
